package com.oweight.sagacious.auth.client.interceptor;

import com.oweight.sagacious.auth.client.config.ServiceAuthConfig;
import com.oweight.sagacious.auth.client.config.UserAuthConfig;
import com.oweight.sagacious.auth.client.jwt.ServiceAuthUtil;
import com.oweight.sagacious.auth.common.constatns.CommonConstants;
import com.oweight.sagacious.common.context.BaseContextHandler;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 服务访问配置token
 *
 * @author 周广明
 * @version v1 2019/10/24 19:16
 */
@Slf4j
@Component
public class OkHttpTokenInterceptor implements Interceptor {

    @Autowired
    @Lazy
    private ServiceAuthUtil serviceAuthUtil;

    @Autowired
    @Lazy
    private ServiceAuthConfig serviceAuthConfig;

    @Autowired
    @Lazy
    private UserAuthConfig userAuthConfig;

    /**
     * @param chain
     * @return okhttp3.Response
     * @author zhougm
     * @version 2019/11/8 14:38
     */
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {

        Request newRequest;
        String userTokenHeader = userAuthConfig.getTokenHeader();
        String clientTokenHeader = serviceAuthConfig.getTokenHeader();
        String userToken = BaseContextHandler.getToken();

        Request.Builder builder = chain.request().newBuilder();
        if (chain.request().url().toString().contains("client/token")) {
            // 如果是获取客户端Token则无需带
            newRequest = builder.header(userTokenHeader, userToken).build();
        } else {
            newRequest = builder.header(userTokenHeader, userToken).header(clientTokenHeader, serviceAuthUtil.getClientToken()).build();
        }

        Response response = chain.proceed(newRequest);
        if (HttpStatus.FORBIDDEN.value() == response.code()) {
            assert response.body() != null;
            if (response.body().string().contains(String.valueOf(CommonConstants.EX_CLIENT_INVALID_CODE))) {
                log.info("Client Token Expire,Retry to request...");
                serviceAuthUtil.refreshClientToken();
                newRequest = builder.header(userTokenHeader, userToken).header(clientTokenHeader, serviceAuthUtil.getClientToken()).build();
                response = chain.proceed(newRequest);
            }
        }
        return response;
    }
}
